package com.kaifamiao.jdbc.core;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

public class StatementTest {

    public static void main(String[] args) throws Exception{
        Properties props = new Properties();

        // 获得 StatementTest 类对应的 Class实例
        final Class<?> c = StatementTest.class;
        // 获得用于读取 类路径根目录("/") 下 指定文件("jdbc.properties") 的字节输入流
        InputStream in = c.getResourceAsStream( "/jdbc.properties" );
        // 从字节输入流中加载 "属性名-属性值" 对 到 Properties集合中
        props.load( in ); // IOException
        // 关闭字节输入流
        in.close();

        String connect = props.getProperty( "connect" , "mysql");
        connect = connect.isBlank() ? "mysql" : connect;

        String driverClassName = props.getProperty( "jdbc.connection." + connect + ".driver" );
        String url = props.getProperty( "jdbc.connection." + connect + ".url" );
        String user = props.getProperty( "jdbc.connection." + connect + ".user" );
        String password = props.getProperty( "jdbc.connection." + connect + ".password" );

        // 加载并注册驱动
        Class.forName( driverClassName );
        // 建立连接
        Connection conn = DriverManager.getConnection( url, user, password );
        // 创建Statement对象
        Statement stmt = conn.createStatement();
        System.out.println( stmt );

        // "执行SQL": 发送SQL给数据库服务器、获取数据库服务器返回的结果
        int count = stmt.executeUpdate( "CREATE TABLE t_pandas ( id NUMBER(5), name VARCHAR2(20), PRIMARY KEY(id) )" );
        // 输出返回值 (因为我们执行的是 DDL 语句，因此一定返回 0 )
        System.out.println( count );

        // 释放资源
        stmt.close();
        conn.close();
    }

}
